package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 刘付磊
 * @date 2021/10/14 0014
 */
@RequestMapping("/employee")
@RestController
@Slf4j
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        R<Employee> login = employeeService.login(employee);
        if (login.getCode() == 1) {
            request.getSession().setAttribute("employee", login.getData().getId());

        }
        return login;
    }

    @PostMapping("logout")
    public R<String> logout(HttpServletRequest request) {
        R<String> logout = employeeService.logout(request);
        return logout;
    }

    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        //1.设置初始密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //2.设置修改时间和创造时间
        /*employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());*/
        //3.设置修改对象的ID 和 创建对象的ID
        /*Long id = (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser(id);
        employee.setUpdateUser(id);*/
        employeeService.save(employee);
        /*R<String> save = employeeService.save(request, employee);
        log.info("123456"+save);*/
        return R.success("成功添加员工");
    }

    @GetMapping("/page")
    public R<Page<Employee>> findPageEndName(String name,int page, int pageSize) {
        //1.构造分页器构造器
        R<Page<Employee>> pen = employeeService.findPageEndName(name, page, pageSize);
        return pen;
    }

    @PutMapping
    public R<String> update(@RequestBody Employee employee) {
        log.info("改状态");
        /*Long id = (Long) request.getSession().getAttribute("employee");

        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(id);*/
        employeeService.updateById(employee);
        return R.success("员工信息修改成功");
    }
  @GetMapping("/{id}")
    public R<Employee> findOne(@PathVariable Long id){
      Employee byId = employeeService.getById(id);
      return R.success(byId);
    }
}
